﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace cpktools
{
    class XorCrypt
    {
        int st, mu;

        public XorCrypt(int s, int m)
        {
            st = s;
            mu = m;
        }

        public byte[] XorRead(Stream input, int count)
        {
            byte[] ret = new byte[count];
            BinaryReader br = new BinaryReader(input);
            int xor_para = st;
            for (int i = 0; i < count; i++)
            {
                ret[i]=(byte)(br.ReadByte() ^ (byte)xor_para);
                xor_para *= mu;
                xor_para &= 0xFF;
            }
            return ret;
        }
        public void XorWrite(Stream output, byte[] bytes, int count = 0)
        {
            BinaryWriter bw = new BinaryWriter(output);
            int xor_para = st;
            if (count == 0) count = bytes.Length;
            byte[] outb=new byte[count];
            for (int i = 0; i < count; i++)
            {
                outb[i] = (byte)(bytes[i] ^ (byte)xor_para);
                xor_para *= mu;
                xor_para &= 0xFF;
            }
            bw.Write(outb, 0, count);
        }
    }
}
